﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using ExitGames.Logging;
using ExitGames.Logging.Log4Net;
using log4net;
using log4net.Config;
using Photon.SocketServer;
using WorldOfSuperpowers.Handler;
using WorldOfSuperpowers_COMMON;
using LogManager = ExitGames.Logging.LogManager;

namespace WorldOfSuperpowers
{
    public class MasterServer:ApplicationBase
    {
       
        public static Dictionary<OperationCode,BaseHandler> handlerDic = new Dictionary<OperationCode, BaseHandler>();

        public static readonly ILogger log = ExitGames.Logging.LogManager.GetCurrentClassLogger();

        protected override PeerBase CreatePeer(InitRequest initRequest)
        {
            return new MasterClientPeer(initRequest);
        }

        protected override void Setup()
        {
            //#region 日志功能注册
            LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);
            GlobalContext.Properties["Photon:ApplicationLogPath"] = Path.Combine(this.ApplicationRootPath, "log");
            GlobalContext.Properties["LogFileName"] = "[MyServer%" + this.ApplicationName + "]";
            XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(this.BinaryPath, "log4net.config")));

            log.Debug("开始注册处理器");
            RegistAllHandler();


            log.Debug("服务器启动成功");
        }

        /// <summary>
        /// 注册全部处理器
        /// </summary>
        public void RegistAllHandler()
        {
            // 启动全部子类的注册函数
            Assembly a = Assembly.GetAssembly(typeof(BaseHandler));
            int count = 0;
            foreach (Type t in a.GetTypes())
            {
                //是否是類
                if (t.IsClass)
                {
                    //是否是當前類的派生類
                    if (t.IsSubclassOf(typeof(BaseHandler)))
                    {
                        count += 1;
                        object handler = Activator.CreateInstance(t);
                        //t.InvokeMember("SayHello", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, new object[] { })
                        t.InvokeMember("RegistOnMaster",BindingFlags.InvokeMethod, null, handler,
                            new object[] { });
                        log.Debug("发现第"+count+"个子类:"+t.Name);
                    }
                }
            }
        }


        protected override void TearDown()
        {
            
        }
    }
}
